package design.mode.prototype;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 采用浅拷贝的方式创建 newKeywords。
 * 对于需要更新的 SearchWord 对象，我们再使用深度拷贝的方式创建一份新的对象，
 * 替换 newKeywords 中的老对象。毕竟需要更新的数据是很少的。
 * 这种方式即利用了浅拷贝节省时间、空间的优点，
 * 又能保证 currentKeywords 中的中数据都是老版本的数据。
 *
 * @author ZhongMingde on 2021/10/28
 */

public class Demo5 {
    private HashMap<String, SearchWord> currentKeywords = new HashMap();
    private long lastUpdateTime = -1;

    public void refresh() {
        HashMap<String, SearchWord> newKeyWords = (HashMap<String, SearchWord>) currentKeywords.clone();
        // 从数据库中取出更新时间>lastUpdateTime的数据，放入到newKeywords中
        List<SearchWord> toBeUpdatedSearchWords = getSearchWords(lastUpdateTime);
        long maxNewUpdatedTime = lastUpdateTime;
        for (SearchWord searchWord : toBeUpdatedSearchWords) {
            if (searchWord.getLastUpdateTime() > maxNewUpdatedTime) {
                maxNewUpdatedTime = searchWord.getLastUpdateTime();
            }
            // 直接将需要更新的旧对象从浅拷贝集合中移除，而不是去更新，避免影响老版本的数据
            if (newKeyWords.containsKey(searchWord.getKeyWord())) {
                newKeyWords.remove(searchWord.getKeyWord());
            }
            newKeyWords.put(searchWord.getKeyWord(), searchWord);
        }
    }

    private List<SearchWord> getSearchWords(long lastUpdateTime) {
        return Collections.emptyList();
    }

    class SearchWord {
        private long lastUpdateTime;
        private int count;
        private String keyWord;

        public SearchWord(String keyWord, int count, long lastUpdateTime) {
            this.lastUpdateTime = lastUpdateTime;
            this.count = count;
            this.keyWord = keyWord;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public long getLastUpdateTime() {
            return lastUpdateTime;
        }

        public void setLastUpdateTime(long lastUpdateTime) {
            this.lastUpdateTime = lastUpdateTime;
        }

        public String getKeyWord() {
            return keyWord;
        }

        public void setKeyWord(String keyWord) {
            this.keyWord = keyWord;
        }
    }
}
